package com.heima.leetcode.practice;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 116. 填充每个节点的下一个右侧节点指针
 * @date 2025/5/23 9:59
 */
public class E116 {

    public static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    /**
     * 方法一：层序遍历
     * @param root 根节点
     * @return 填充节点的next指针后的根节点
     */
    @SuppressWarnings("all")
    public Node connect(Node root) {
        Queue<Node> queue = new LinkedList<>();
        if (root == null) return root;
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            Node prev = null;
            for (int i = 0; i < size; i++) {
                Node last = queue.poll();
                if (last.left != null) {
                    queue.offer(last.left);
                }
                if (last.right != null) {
                    queue.offer(last.right);
                }
                if (prev != null) prev.next = last;
                prev = last;
            }
        }
        return root;
    }
}
